﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using MS.InformationManagement.Support.Constants;
using System.Text;

namespace MS.InformationManagement.Documents.ObjectDef.ItemReceivers.HolidayEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class HolidayEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            if (properties.List.Title.Equals("Dias Festivos"))
            {
                this.EventFiringEnabled = false;
                try
                {
                    StringBuilder camlQuery = new StringBuilder("<Where>");
                    camlQuery
                        .Append("<Eq>")
                        .Append(string.Format("<FieldRef Name='{0}' />", CustomSiteColumns.FIELD_FECHA_FESTIVO))
                        .Append(string.Format("<Value IncludeTimeValue='FALSE' Type='DateTime'>{0}</Value>", properties.AfterProperties[CustomSiteColumns.FIELD_FECHA_FESTIVO]))
                        .Append("</Eq></Where>");

                    SPQuery query = new SPQuery { Query = camlQuery.ToString() };
                    SPListItemCollection items = properties.List.GetItems(query);

                    if (items.Count > 0)
                    {
                        properties.Cancel = true;
                        properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                        properties.RedirectUrl = "/_layouts/error.aspx?ErrorText=Ya existe un día festivo para esa fecha.";
                        //properties.Status = SPEventReceiverStatus.CancelWithError;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    this.EventFiringEnabled = true;
                    SPUtility.TransferToErrorPage("Ya existe un día festivo para esa fecha");
                }

            }
        }

        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
            if (properties.List.Title.Equals("Dias Festivos"))
            {
                this.EventFiringEnabled = false;
                try
                {
                    StringBuilder camlQuery = new StringBuilder("<Where>");
                    camlQuery
                        .Append("<And><Eq>")
                        .Append(string.Format("<FieldRef Name='{0}' />", CustomSiteColumns.FIELD_FECHA_FESTIVO))
                        .Append(string.Format("<Value IncludeTimeValue='FALSE' Type='DateTime'>{0}</Value>", properties.AfterProperties[CustomSiteColumns.FIELD_FECHA_FESTIVO]))
                        .Append("</Eq><Neq>")
                        .Append(string.Format("<FieldRef Name='ID' /><Value Type='Counter'>{0}</Value>", properties.ListItemId))
                        .Append("</Neq></And></Where>");

                    SPQuery query = new SPQuery { Query = camlQuery.ToString() };
                    SPListItemCollection items = properties.List.GetItems(query);

                    if (items.Count > 0)
                    {
                        properties.Cancel = true;
                        properties.ErrorMessage = "Ya existe un día festivo para esa fecha diferente al elemento que intenta actualizar.";
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    this.EventFiringEnabled = true;
                }

            }
        }
    }
}
